package _07_串;

/**
 * https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/
 *
 * @Author: haogege
 * @Date: 2021/9/19
 */
public class _557_反转字符串中的单词III {

    public static void main(String[] args) {

        String str = "Let's take LeetCode contest";

        System.out.println(reverseWords(str));

    }

    public static String reverseWords(String s) {
        char[] chars = s.toCharArray();
        int begin = 0, end = 0;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == ' ') {
                end = i - 1;
                reverseString(chars, begin, end);
                begin = i + 1;
            }
        }
        reverseString(chars, begin, s.length() - 1);
        return new String(chars);
    }

    public static void reverseString(char[] s, int left, int right) {
        while (left < right) {
            char temp = s[left];
            s[left++] = s[right];
            s[right--] = temp;
        }
    }

}
